from django.shortcuts import render

# Create your views here.
# GET /oauth/qq/authorization/?next=<登录后访问页面url>
from rest_framework import request, status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
# from rest_framework.settings import api_settings
from rest_framework.views import APIView

from oauth.exceptions import QQAPIError
from oauth.models import OAuthQQUser
from oauth.serializers import OAuthQQUserSerializer
from oauth.utils import OAuthQQ


class QqLoginView(APIView):
    """获取qq登录的网址"""

    def get(self, request):
        next = request.query_params.get("next", "/")
        oauth = OAuthQQ(state=next)
        login_url = oauth.get_login_url()

        return Response({"login_url": login_url})


class QQAuthUserView(GenericAPIView):
    serializer_class = OAuthQQUserSerializer

    def post(self, request):
        """
        保存QQ登录绑定数据:
        1. 获取参数并进行校验(参数完整性，手机号格式，短信验证码是否正确，access_token是否有效)
        2. 保存绑定QQ登录数据
        3. 返回应答，绑定成功
        """
        # 1 获取参数并进行校验（参数完整性，手机号格式，短信验证码是否正确，access_token是否有效）
        serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        serializer.is_valid(raise_exception=True)

        # 2 保存绑定QQ登录数据
        serializer.save()

        # 3 返回应答，绑定成功
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def get(self, request):
        """获取openid并处理"""
        # 1. 通过获取查询字符串的方式获取code
        code = request.query_params.get("code")

        # 2. 根据code 获取access_token
        # 3. 根据access_token获取openid
        try:
            access_token = OAuthQQ().get_access_token(code)
            openid = OAuthQQ().get_openid(access_token)
        except QQAPIError as e:
            return Response({"message": "QQ服务器错误"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 4. 根据openid获取user_id并判断是否绑定并返回：
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist as e:
            # 用户未绑定，返回加密后的openid
            token = OAuthQQ.generate_save_user_token(openid)
            return Response({
                "access_token": token,
            })
        else:
            # 用户绑定了，返回下面的字典
            user = oauth_user.user
            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return Response({
                "user_id": user.id,
                "username": user.username,
                "token": token,
            })
